package com.seculab.login.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.seculab.common.util.CipherUtil;
import com.seculab.member.domain.Member;
import com.seculab.member.service.MemberService;

@Controller
@RequestMapping("/login")
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private MemberService memberService;
	
	@RequestMapping(value="login", method=RequestMethod.GET)
	public void login(HttpSession session) throws Exception {
	}	

	@RequestMapping(value="login", method=RequestMethod.POST)
	public String login(Model model, Member param, HttpSession session, HttpServletRequest request
			, HttpServletResponse response) throws Exception {
		Cookie cookies[] = request.getCookies();
		
		logger.info("id is {}, save is {}", param.getId(), param.getId_save());
		
		if(param.getId_save() != null && !"".equals(param.getId_save())) {
			if(param.getId_save().equals("Y")){
				Cookie cookie = new Cookie("seculab", param.getId());
				cookie.setMaxAge(0);
				response.addCookie(cookie);
				
				cookie = new Cookie("seculab", param.getId());
				logger.info("{}", "cookie is added");
				cookie.setMaxAge(60*60*24*30);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		} else {
			logger.info("cookies length {}", cookies.length);
			if(cookies != null && cookies.length > 1) {
				Cookie cookie = new Cookie("seculab", param.getId());
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
		
		String password = CipherUtil.encrypt(param.getPassword());
		param.setPassword(password);
		
		Member member = memberService.getMember(param);
		if(member != null) {
			session.setAttribute("member", member);
			return "redirect:/app/board/boardList";
		} else {
			return "redirect:/app/login/login";
		}
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session) throws Exception {
		session.invalidate();

		return "redirect:/app/main/main";
	}	
	
}
